<script setup lang="ts">
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { authService } from '@/services/apiService'
import { initializeTokenManager } from '@/utils/tokenManager'
import { ElForm, ElFormItem, ElInput, ElButton, ElCard, ElMessage } from 'element-plus'

// 表单数据
const registerForm = ref({
  username: '',
  email: '',
  password: '',
  confirmPassword: ''
})

const loading = ref(false)
const errors = ref<Record<string, string>>({})

const router = useRouter()
const userStore = useUserStore()

// 验证表单
const validateForm = (): boolean => {
  errors.value = {}
  let isValid = true

  if (!registerForm.value.username.trim()) {
    errors.value.username = '请输入用户名'
    isValid = false
  }

  if (!registerForm.value.email.trim()) {
    errors.value.email = '请输入邮箱'
    isValid = false
  } else {
    // 简单的邮箱格式验证
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
    if (!emailRegex.test(registerForm.value.email)) {
      errors.value.email = '请输入有效的邮箱地址'
      isValid = false
    }
  }

  if (!registerForm.value.password) {
    errors.value.password = '请输入密码'
    isValid = false
  } else if (registerForm.value.password.length < 6) {
    errors.value.password = '密码长度至少6位'
    isValid = false
  }

  if (registerForm.value.password !== registerForm.value.confirmPassword) {
    errors.value.confirmPassword = '两次输入的密码不一致'
    isValid = false
  }

  return isValid
}

// 处理注册
const handleRegister = async () => {
  if (!validateForm()) {
    return
  }

  loading.value = true
  try {
    const response = await authService.register(
      registerForm.value.username,
      registerForm.value.email,
      registerForm.value.password
    )

    // 保存用户信息到store
    //注册用户默认普通用户，level设为0
    userStore.login({
      access: response.access,
      refresh: response.refresh,
      id: response.user.uid,
      username: response.user.username,
      email: response.user.email,
      avatar: response.user.avatar,
      level: 0
    })
    
    //本地持久化登录状态
    localStorage.setItem('access', response.access)
    localStorage.setItem('refresh', response.refresh)
    localStorage.setItem('userInfo', JSON.stringify(userStore.userInfo))
    
    // 初始化token管理器
    if (response.refresh) {
      initializeTokenManager(response.refresh)
    }
    
    // 跳转到首页
    router.push('/')
  } catch (error: any) {
    console.error('注册失败:', error)
    ElMessage.error('注册失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 跳转到登录页面
const goToLogin = () => {
  router.push('/login')
}
</script>

<template>
  <div class="auth-container">
    <el-card class="auth-card">
      <template #header>
        <h2>用户注册</h2>
      </template>
      
      <el-form @submit.prevent="handleRegister" class="auth-form">
        <div v-if="errors.general" class="error-message general-error">
          {{ errors.general }}
        </div>
        
        <el-form-item label="用户名" :error="errors.username">
          <el-input
            v-model="registerForm.username"
            placeholder="请输入用户名"
            clearable
          />
        </el-form-item>
        
        <el-form-item label="邮箱" :error="errors.email">
          <el-input
            v-model="registerForm.email"
            type="email"
            placeholder="请输入邮箱"
            clearable
          />
        </el-form-item>
        
        <el-form-item label="密码" :error="errors.password">
          <el-input
            v-model="registerForm.password"
            type="password"
            placeholder="请输入密码（至少6位）"
            show-password
          />
        </el-form-item>
        
        <el-form-item label="确认密码" :error="errors.confirmPassword">
          <el-input
            v-model="registerForm.confirmPassword"
            type="password"
            placeholder="请再次输入密码"
            show-password
          />
        </el-form-item>
        
        <div class="form-actions">
          <el-button 
            type="success" 
            native-type="submit" 
            :loading="loading" 
            style="width: 100%"
          >
            {{ loading ? '注册中...' : '注册' }}
          </el-button>
        </div>
      </el-form>
      
      <div class="auth-footer">
        <p>已有账号？<a href="#" @click.prevent="goToLogin">立即登录</a></p>
      </div>
    </el-card>
  </div>
</template>

<style scoped>
.auth-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: calc(100vh - 120px);
  padding: 20px;
}

.auth-card {
  width: 100%;
  max-width: 400px;
}

.auth-card h2 {
  text-align: center;
  margin: 0;
  color: #333;
}

.auth-form {
  margin-bottom: 20px;
}

.form-actions {
  margin-top: 30px;
}

.auth-footer {
  text-align: center;
  color: #666;
}

.auth-footer a {
  color: #007bff;
  text-decoration: none;
}

.auth-footer a:hover {
  text-decoration: underline;
}
</style>